import json
import os

from alipay import AliPay
from django import http
from django.shortcuts import render
from django.views import View

from meiduo_mall.settings.dev import ALIPAY_APPID, ALIPAY_DEBUG, ALIPAY_RETURN_URL, ALIPAY_NOTIFY_URL
from orders.models import OrderInfo
from meiduo_mall.utils.response_code import RETCODE


class AlipayurlView(View):
    def get(self, request, order_id):
        # 接收

        # 验证
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except:
            return http.JsonResponse({"code": RETCODE.PARAMERR, 'errmsg': '订单编号不存在'})
        # 创建支付宝对象
        alipay = AliPay(
            appid=ALIPAY_APPID,  # 自己的ａｐｐｉｄ
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'alipay/app_private_key.pem'),
            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'alipay/app_public_key.pem'),
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=ALIPAY_DEBUG  # 默认False
        )
        # 生成支付宝链接
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order.order_id,
            total_amount=str(order.total_amount),
            subject='美多商城',
            return_url=ALIPAY_RETURN_URL,
            notify_url=ALIPAY_NOTIFY_URL  # 可选, 不填则使用默认notify url
        )

        url = 'https://openapi.alipaydev.com/gateway.do' + order_string
        # url = json.dumps(url)
        # 响应
        return http.JsonResponse({"code": RETCODE.OK, 'errmsg': 'ok', 'alipay_url': url})
